package com.zjhd.sealcutting.service.impl;

import com.google.common.collect.Maps;
import com.zjhd.sealcutting.dao.*;
import com.zjhd.sealcutting.domain.*;
import com.zjhd.sealcutting.param.WorksInfoSearchQuery;
import com.zjhd.sealcutting.service.WorksInfoService;
import com.zjhd.sealcutting.utils.DateUtil;
import com.zjhd.sealcutting.utils.idgenerator.Sequence;
import com.zjhd.sealcutting.utils.response.ResponseResult;
import com.zjhd.sealcutting.utils.response.ResultGenerator;
import com.zjhd.sealcutting.vo.SearchResult;
import com.zjhd.sealcutting.vo.WorksInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * TODO  作品管理
 *
 * @author wangchao
 * @version 1.0
 * @date 2020/12/1 9:48
 */
@Service
public class WorksInfoServiceImpl implements WorksInfoService {

    @Autowired
    private WorksInfoMapper worksInfoMapper;

    @Autowired
    private WorksPictureMapper worksPictureMapper;

    @Autowired
    private WorksEnclosureMapper worksEnclosureMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WorksCommentMapper worksCommentMapper;

    @Autowired
    private CreativeTaskMapper creativeTaskMapper;

    /**
     * TODO  查询作品列表
     * @author wangchao
     * @date 2020/12/1 15:44
     * @param 
     * @return 
     */
    @Override
    public SearchResult queryWorksInfoParamlist(WorksInfoSearchQuery param) throws Exception {
        //定义map 封装查询参数到map中
        Map<String, Object> map = Maps.newLinkedHashMap();
        if(param.getWorkStatus()!=null){
            map.put("workStatus",param.getWorkStatus());
        }
        if(param.getWorkType()!=null){
            map.put("workType",param.getWorkType());
        }
        if(StringUtils.isNotBlank(param.getKeyWord())){
            map.put("keyWord",param.getKeyWord());
        }
        //当前页  分页数
        map.put("pageIndex", (Integer.parseInt(param.getPageIndex()) - 1) * Integer.parseInt(param.getPageSize()));
        map.put("pageSize", Integer.parseInt(param.getPageSize()));
        //查询用户信息
        UserInfo userInfo=userInfoMapper.selectByPrimaryKey(param.getUserId());
        if(userInfo!=null){
            if(!userInfo.getUserGroup().equals("1")){
                map.put("creatorId", userInfo.getId());
            }
        }
        List<WorksInfo> worksInfos=worksInfoMapper.queryParamWorksInfoList(map);
        long totalCount=worksInfoMapper.queryParamWorksInfoCount(map);
        List<WorksInfoVo> worksInfoVos=new ArrayList<>();
        for(WorksInfo worksInfo:worksInfos){
            WorksInfoVo worksInfoVo=new WorksInfoVo();
            List<WorksPicture> worksPictures=worksPictureMapper.queryByWorkId(worksInfo.getId());
            List<WorksEnclosure> worksEnclosures=worksEnclosureMapper.queryByWorkId(worksInfo.getId());
            //查询作品所属展览
            String exhibitionName=null;
            if(worksInfo.getWorkType().equals(0)){
                exhibitionName=creativeTaskMapper.queryByWorkId(worksInfo.getId());
            }else {
                exhibitionName=creativeTaskMapper.queryByWorkId(worksInfoMapper.queryByRelatedWorksId(worksInfo.getId()));
            }
            worksInfoVo.setExhibitionName(exhibitionName);
            worksInfoVo.setReviewsNumber(worksCommentMapper.queryByWorkIdReviewsIdCount(worksInfo.getId()));
            worksInfoVo.setWorksInfo(worksInfo);
            worksInfoVo.setWorksPicture(worksPictures);
            worksInfoVo.setWorksEnclosures(worksEnclosures);
            worksInfoVos.add(worksInfoVo);
        }
        if(worksInfoVos.size()>0){
            return new SearchResult.Builder<List<WorksInfoVo>>()
                    .setCurrent(Integer.parseInt(param.getPageIndex()))
                    .setPageSize(Integer.parseInt(param.getPageSize()))
                    .setTotalCount(totalCount)
                    .setPagedItems(worksInfoVos == null ? new ArrayList() : worksInfoVos)
                    .build();
        }else {
            return new SearchResult.Builder().setPagedItems(new ArrayList()).build();
        }
    }

    /**
     * TODO  新增作品
     * @author wangchao
     * @date 2020/12/1 15:47
     * @param
     * @return
     */
    @Override
    @Transactional
    public ResponseResult insertWorksInfo(WorksInfoVo worksInfoVo) throws Exception {
        try {
            if(worksInfoVo!=null && worksInfoVo.getWorksInfo()!=null) {
                long id=new Sequence().nextId();
                TimeUnit.MILLISECONDS.sleep(100);
                if(StringUtils.isNotBlank(worksInfoVo.getFirstDraftWorkId())){
                    //终稿
                    worksInfoVo.getWorksInfo().setWorkType(1);
                    worksInfoVo.getWorksInfo().setWorkStatus(0);
                    //修改初稿状态和关联终稿字段
                    WorksInfo worksInfo=new WorksInfo();
                    worksInfo.setId(worksInfoVo.getFirstDraftWorkId());
                    worksInfo.setRelatedWorksId(String.valueOf(id));
                    worksInfo.setWorkStatus(2);
                    worksInfoMapper.updateByPrimaryKeySelective(worksInfo);
                }else {
                    //初稿
                    worksInfoVo.getWorksInfo().setWorkType(0);
                    worksInfoVo.getWorksInfo().setWorkStatus(0);
                }
                worksInfoVo.getWorksInfo().setUploadTime(DateUtil.getCurrentTime());
                worksInfoVo.getWorksInfo().setId(String.valueOf(id));
                int i = worksInfoMapper.insert(worksInfoVo.getWorksInfo());
                if (i > 0) {
                    for(WorksPicture worksPicture:worksInfoVo.getWorksPicture()){
                        worksPicture.setWorkId(String.valueOf(id));
                        worksPictureMapper.insert(worksPicture);
                    }
                    for(WorksEnclosure worksEnclosure:worksInfoVo.getWorksEnclosures()){
                        worksEnclosure.setWorkId(String.valueOf(id));
                        worksEnclosureMapper.insert(worksEnclosure);
                    }
                    return ResultGenerator.genSuccessResult("新增作品成功!");
                } else {
                    return ResultGenerator.genFailResult("新增作品失败!");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("新增作品失败!");
    }

    /**
     * TODO  修改作品
     * @author wangchao
     * @date 2020/12/1 15:47
     * @param
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateWorksInfo(WorksInfoVo worksInfoVo) throws Exception {
        try {
            if(worksInfoVo!=null && worksInfoVo.getWorksInfo()!=null) {
                int i = worksInfoMapper.updateByPrimaryKeySelective(worksInfoVo.getWorksInfo());
                if (i > 0) {
                    //删除图片和附件
                    worksPictureMapper.deleteByWorkId(worksInfoVo.getWorksInfo().getId());
                    worksEnclosureMapper.deleteByWorkId(worksInfoVo.getWorksInfo().getId());
                    for(WorksPicture worksPicture:worksInfoVo.getWorksPicture()){
                        worksPicture.setWorkId(worksInfoVo.getWorksInfo().getId());
                        worksPictureMapper.insert(worksPicture);
                    }
                    for(WorksEnclosure worksEnclosure:worksInfoVo.getWorksEnclosures()){
                        worksEnclosure.setWorkId(worksInfoVo.getWorksInfo().getId());
                        worksEnclosureMapper.insert(worksEnclosure);
                    }
                    return ResultGenerator.genSuccessResult("修改作品成功!");
                } else {
                    return ResultGenerator.genFailResult("修改作品失败!");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("修改作品失败!");
    }

    /**
     * TODO 删除作品
     * @author wangchao
     * @date 2020/12/1 15:47
     * @param
     * @return
     */
    @Override
    @Transactional
    public ResponseResult deleteWorksInfo(String id) throws Exception {
        try {
            int i=worksInfoMapper.deleteByPrimaryKey(id);
            if(i>0){
                //删除图片和附件
                worksPictureMapper.deleteByWorkId(id);
                worksEnclosureMapper.deleteByWorkId(id);
                return ResultGenerator.genSuccessResult("删除作品成功!");
            }else {
                return ResultGenerator.genFailResult("删除作品失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("删除作品失败!");
    }

    /**
     * TODO  根据作品ID查询作品详情
     * @author wangchao
     * @date 2020/12/1 15:48
     * @param
     * @return
     */
    @Override
    public WorksInfoVo queryByIdWorksInfo(String id) throws Exception {
        WorksInfoVo worksInfoVo=new WorksInfoVo();
        WorksInfo worksInfo=worksInfoMapper.selectByPrimaryKey(id);
        List<WorksPicture> worksPictures=worksPictureMapper.queryByWorkId(id);
        List<WorksEnclosure> worksEnclosures=worksEnclosureMapper.queryByWorkId(id);
        worksInfoVo.setWorksInfo(worksInfo);
        worksInfoVo.setWorksPicture(worksPictures);
        worksInfoVo.setWorksEnclosures(worksEnclosures);
        return worksInfoVo;
    }

    /**
     * TODO
     * @author wangchao
     * @date 2020/12/3 13:38
     * @param 
     * @return 
     */
    @Override
    public List<WorksInfo> queryByCreaterIdWorks(Integer userId) throws Exception {
        List<WorksInfo> worksInfos=new ArrayList<>();
        //查询用户信息
        UserInfo userInfo=userInfoMapper.selectByPrimaryKey(userId);
        if(userInfo!=null){
            if(userInfo.getUserGroup().equals("1")){
                worksInfos=worksInfoMapper.queryWorks();
            }else {
                worksInfos=worksInfoMapper.queryByCreaterIdWorks(userId);
            }
        }
        return worksInfos;
    }

    /**
     * TODO  作品代传
     * @author wangchao
     * @date 2020/12/28 11:39
     * @param
     * @return
     */
    @Override
    @Transactional
    public ResponseResult generationUploadWorksInfo(WorksInfoVo worksInfoVo) throws Exception {
        try {
            if(worksInfoVo!=null && worksInfoVo.getWorksInfo()!=null) {
                long id=new Sequence().nextId();
                TimeUnit.MILLISECONDS.sleep(100);
                //代传初稿 作品直接投稿状态
                worksInfoVo.getWorksInfo().setWorkType(0);
                worksInfoVo.getWorksInfo().setWorkStatus(1);
                worksInfoVo.getWorksInfo().setUploadTime(DateUtil.getCurrentTime());
                worksInfoVo.getWorksInfo().setId(String.valueOf(id));
                int i = worksInfoMapper.insert(worksInfoVo.getWorksInfo());
                //创建投稿任务 关联展览和词条
                CreativeTask creativeTask=new CreativeTask();
                creativeTask.setExhibitionId(worksInfoVo.getExhibitionId());
                creativeTask.setCreateTime(DateUtil.getCurrentTime());
                creativeTask.setEntryId(worksInfoVo.getEntryId());
                creativeTask.setWorkId(String.valueOf(id));
                creativeTask.setDistributionId(worksInfoVo.getAuthorId());
                creativeTask.setState(1);
                creativeTaskMapper.insert(creativeTask);
                if (i > 0) {
                    for(WorksPicture worksPicture:worksInfoVo.getWorksPicture()){
                        worksPicture.setWorkId(String.valueOf(id));
                        worksPictureMapper.insert(worksPicture);
                    }
                    for(WorksEnclosure worksEnclosure:worksInfoVo.getWorksEnclosures()){
                        worksEnclosure.setWorkId(String.valueOf(id));
                        worksEnclosureMapper.insert(worksEnclosure);
                    }
                    return ResultGenerator.genSuccessResult("代传作品成功!");
                } else {
                    return ResultGenerator.genFailResult("代传作品失败!");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("代传作品失败!");
    }

}
